<?php
!defined('IN_SYSTEM') && exit('Access Denied!');

if (!function_exists('file_put_contents')) {
	function file_put_contents($file, $data, $append = false) {
		$mode = $append ? 'ab' : 'wb';
		$fp = @fopen($file,$mode) or die("can not open file $file !");
		flock($fp, LOCK_EX);
		$len = fwrite($fp, $data);
		flock($fp, LOCK_UN);
		@fclose($fp);
		return $len;
	}
}

if ( !function_exists('file_get_contents') ) {
	function file_get_contents($file) {
		$fp = @fopen($file,'rb') or die("can not open file $file!");
		flock($fp, LOCK_SH);
		$content = fread($fp, filesize($file));
		flock($fp, LOCK_UN);
		@fclose($fp);
		return $content;
	}
}

if (!function_exists('json_encode')) {
	function json_encode ($a=false) {
		if (is_null($a)) return 'null';
		if ($a === false) return 'false';
		if ($a === true) return 'true';
		if (is_scalar($a)) {
			if (is_float($a)) {
				return floatval(str_replace(",", ".", strval($a)));
			}
			if (is_string($a)) {
				static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
				return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
			} else {
				return $a;
			}
		}
		$isList = true;
		for ($i = 0, reset($a); $i < count($a); $i++, next($a)) {
			if (key($a) !== $i) {
				$isList = false;
				break;
			}
		}
		$result = array();
		if ($isList) {
			foreach ($a as $v) $result[] = json_encode($v);
			return '[' . join(',', $result) . ']';
		} else {
			foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
			return '{' . join(',', $result) . '}';
		}
	}
}
/**
 * 时间戳转化为时间字符串,使用方式和date()函数一致,
 * @param string $format  时间串
 * @param string $timestamp 时间戳，默认为系统时间TIMESTAMP
 */
function gdate($format, $timestamp = TIMESTAMP) {
	$timezone = get_config('timezone');
	return gmdate($format, $timestamp + intval($timezone) * 3600);
}
/**
 * 时间字符串转化为时间戳，使用方式和strtotime()一致
 * @param string $timestr 时间字符串
 */
function gtime($timestr) {
	$timezone = get_config('timezone');
	return function_exists('date_default_timezone_set') ? (strtotime($timestr) - 3600 * $timezone) : strtotime($timestr);
}

//页面跳转,不提示
function goto_page($url) {
	echo '<html><head></head><body><script type="text/javascript">window.location=\''.$url.'\'</script></body></html>';
	exit;
}
/**
 * 获取配置$_G['settings']里的信息
 * @param string $key  要获取的内容
 * @param string $type 类型
 */
function get_config($key, $type=null) {
	global $_G;
	if($type && isset($_G['settings'][$type][$key])) {
		return $_G['settings'][$type][$key];
	}else if(isset($_G['settings'][$key])){
		return $_G['settings'][$key];
	}
	return null;
}

function get_html_dir($dateline, $catename) {
	$htmldir = get_config('htmldir','seo');
	if ( !$htmldir ) {
		return 'html';
	} else {
		return 'html/'.str_replace(array('{y}','{Y}','{m}','{n}','{d}','{j}','{cate}'), array(gdate('y',$dateline),gdate('Y',$dateline),gdate('m',$dateline),gdate('n',$dateline),gdate('d',$dateline),gdate('j',$dateline),rawurlencode($catename)), $htmldir);
	}
}
//创建目录
function make_dir($path) {
	if ( is_dir($path) || strpos($path, '..')!==false ) return false;
	@mkdir($path);
	@fopen($path.'/index.html','wb');
	@chmod($path, 0777);
}
//删除目录
function remove_dir($path) {
	if ( substr($path, -1) == '/' ) {
		$path = substr($path, 0, -1);
	}
	if ( $handle = opendir($path) ) {
		while ( false !== ($d = readdir($handle)) ) {
			if ( $d != '.' && $d != '..' ) {
				if ( is_dir($path.'/'.$d) ) {
					remove_dir($path.'/'.$d);
				} else {
					@unlink($path.'/'.$d);
				}
			}
		}
		closedir($handle);
		@rmdir($path);
	}
}
//获取客户端IP
function get_client_ip() {
	$clientip = '';
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$clientip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$clientip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$clientip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$clientip = $_SERVER['REMOTE_ADDR'];
	}
	preg_match("/[\d\.]{7,15}/", $clientip, $clientipmatches);
	$clientip = $clientipmatches[0] ? $clientipmatches[0] : 'unknown';
	return $clientip;
}

function add_slashes($string) {
	if (!is_array($string)){
		return addslashes($string);
	}
	foreach ($string as $key => $val) {
		$string[$key] = add_slashes($val);
	}
	return $string;
}

function hack_attack($string,$method='get'){
	$match['get']="'|(and|or)\\b.+?(>|<|=|in|like)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
	$match['post']="\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
	$match['cookie']="\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
	if (preg_match("/".$match[strtolower($method)]."/is",$string)==1){
		setlog('attack',"<br><br>IP: ".$_SERVER["REMOTE_ADDR"]."<br>time: ".strftime("%Y-%m-%d %H:%M:%S")."<br>url:".$_SERVER["PHP_SELF"]."<br>method: ".$_SERVER["REQUEST_METHOD"]."<br>args: ".$method."<br>data: ".$string);
		exit();
	}
}

function del_slashes($string) {
	if (!is_array($string)) {
		return stripslashes($string);
	}
	foreach ($string as $key => $val) {
		$string[$key] = del_slashes($val);
	}
	return $string;
}

function obstart() {
	if ( get_config('obstart') && function_exists('ob_gzhandler') ) {
		ob_start('ob_gzhandler');
	} else {
		ob_start();
	}
}

function obclean() {
	ob_end_clean();
	obstart();
}

//是否开启静态模式
function create_html() {
	return get_config('rewrite','seo') == 2;
}


//检查提交
function check_submit($action) {
	if (isset($_POST[$action]) && $_SERVER['REQUEST_METHOD'] == 'POST') {
		return true;
	}
	return false;
}

//字符串过滤
function check_str($string, $isurl = false) {
	$string = preg_replace('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/','',$string);
	$string = str_replace(array("\0","%00","\r"),'',$string);
	empty($isurl) && $string = preg_replace("/&(?!(#[0-9]+|[a-z]+);)/si",'&amp;',$string);
	$string = str_replace(array("%3C",'<'),'&lt;',$string);
	$string = str_replace(array("%3E",'>'),'&gt;',$string);
	$string = str_replace(array('"',"'","\t",'  '),array('&quot;','&#39;','    ','&nbsp;&nbsp;'),$string);
	return trim($string);
}

//是否超级管理员
function is_admin($uid = '') {
	if(!$uid){
		global $_G;
		$uid = $_G['uid'];
	}
	$suadmin = explode(',',SUPERADMIN);
	if(in_array($uid,$suadmin)) {
		return true;
	}
	return false;

}

//检查权限
function ican($pv = null) {
	global $_G;
	return (isset($_G['usergroup']['access'][$pv])?$_G['usergroup']['access'][$pv]:0) || ISADMIN;
}

//设置COOKIE
function set_cookie($var, $val = '', $expire = 0) {
	$expire = $expire > 0 ? TIMESTAMP + $expire : (empty($val) ? (TIMESTAMP - 3600) : 0);
	$s = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	return setcookie(COOKIE_PRE.$var, $val, $expire, COOKIE_PATH, COOKIE_DOMAIN, $s);
}

//字符串截取
function cut_str($str, $len = 0, $dot = '...',$encoding = 'utf-8') {
	if (!$len || strlen($str) <= $len) return $str;
	$tempstr = '';
	$str = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $str);
	if ($encoding == 'utf-8') {
		$n = $tn = $noc = 0;
		while($n < strlen($str)) {
			$t = ord($str[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif (194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif (224 <= $t && $t < 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif (240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif (248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif ($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $len) {
				break;
			}
		}
		if($noc > $len) {
			$n -= $tn;
		}
		$tempstr = substr($str, 0, $n);
	} elseif ($encoding == 'gbk') {
		for ($i=0; $i<$len; $i++) {
			$tempstr .= ord($str{$i}) > 127 ? $str{$i}.$str{++$i} : $str{$i};
		}
	}
	$tempstr = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $tempstr);
	return $tempstr.$dot;
}

//数据大小单位转换
function sizecount($byte) {
	if ($byte < 1024) {
		return $byte.'byte';
	} elseif (($size = round($byte/1024,2)) < 1024) {
		return $size.'KB';
	} elseif (($size = round($byte / (1024*1024),2)) < 1024) {
		return $size.'MB';
	} else {
		return round($byte / (1024*1024*1024),2).'GB';
	}
}

/**
 *  获取$_GET,$_POST,$_COOKIE值
 *  @param string $var 变量 
 *  @param string $method 不区分大小写,允许值 G,P,C分别获取$_GET,$_POST,$_COOKIE值,默认从$_REQUEST取值
 *	@param string $type 类型，允许值为int ,array,float,默认string 
 */
function getGP($var, $method = '', $type = 'string') {
	if (is_array($var)) {
		$rs = array();
		foreach ($var as $k => $v) {
			$rs[$v] = getGP($v,$method, $k);
		}
		return $rs;
	} elseif ($var) {
		$rs = '';
		switch (strtolower($method)) {
			case 'g':
				$rs = isset($_GET[$var]) ? $_GET[$var]:NULL;
				break;
			case 'p':
				$rs = isset($_POST[$var]) ? $_POST[$var]:NULL;
				break;
			case 'c':
				$var = COOKIE_PRE.$var;
				$rs=isset($_COOKIE[$var]) ? $_COOKIE[$var]:NULL;
				break;
			default:
				$rs = isset($_REQUEST[$var]) ? $_REQUEST[$var]:NULL;
		}
		switch (strtolower($type)) {
			case 'int':
				$rs=(int)($rs);
				break;
			case 'array':
				$rs=(array)$rs;
				break;
			case 'float':
				$rs=floatval($rs);
				break;	
			default :
				$rs=trim((string)$rs);
		}
		return $rs;
	}
	return '';
}

//提示信息
function error ($contents = '', $url = '', $ajump = true, $litime = 3000) {
	$message = array();global $_G;
	if (is_array($contents)) {
		foreach ($contents as $value) $content .= "<li>$value</li>\n"; 
	} else {
		$content = "<li>$contents</li>\n";
	}
	if ( $ajump ) {
		if ($url == "") {
			$nav = "<a href='javascript:history.back();'>如果您的浏览器没自动跳转，请点击这里</a>";
			$goto = "<script>setTimeout(\"history.back();\",{$litime});</script>";
		} else {
			$nav = "<a href='$url'>如果您的浏览器没自动跳转，请点击这里</a>";
			$goto = "<script>setTimeout(\"window.location.href='{$url}';\",{$litime});</script>";
		}
	} else {
		$nav = "<a href='{$url}'>点击这里返回</a>";
		$goto = '';
	}
	if ( file_exists(THEME_ROOT.'message.tpl.php') ) {
		include template('message');
	} else {
		echo '
		<head>
			<title>',$_G['settings']['sitename'],'提示信息</title>
			<meta http-equiv="content-type" content="text/html; charset=utf-8" />
			<style type="text/css">
			body {background:#f0f0f0;text-align:center;}
			table {width:500px;margin:0 auto;}
			th {background:#F9FAF9;padding:8px;font-size:14px;}
			td {background:#fff;padding:8px;font-size:12px;}
			</style>
		</head>
		<body>
			<table cellspacing="0">
				<tr><th>提示信息</th></tr>
				<tr>
					<td align="left"><ol>'.$content.'</ol></td>
				</tr>
				<tr>
					<td align="center">'.$nav.'</td>
				</tr>
			</table>
			'.$goto.'
		</body>
		</html>';
	}
	exit();
}

function libfile($file=null){
	if(file_exists(BASE_ROOT.'./includes/'.$file)){
		return BASE_ROOT.'./includes/'.$file;
	}
}

function random($length,$string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') {
	$rstr = '';
	$strlen = strlen($string);
	for ($i=0; $i<$length; $i++) {
		$rstr .= $string{mt_rand(0,$strlen-1)};	
	}
	return $rstr;
}

function get_cache($cachename) {
	global $_G;
	if(isset($_G['caches'][$cachename]) ){
		return $_G['caches'][$cachename] ;
	}
	$_G['caches'][$cachename] = $_G['cache']->get($cachename);
	if (!$_G['caches'][$cachename]) {
		recache($cachename);
		$_G['caches'][$cachename] = $_G['cache']->get($cachename);
	}
	return $_G['caches'][$cachename];
}

function admintemplate($tpl, $ext = 'tpl.php') {
	$tpl_file = ADMIN_ROOT.'template/'.$tpl.'.'.$ext;
	$compiledtplfile = DATA_DIR.'cache/admintemplates/'.str_replace('/', '_', $tpl).'.tpl.php';
	if(!file_exists($compiledtplfile) || @filemtime($tpl_file) > @filemtime($compiledtplfile)){
    		!is_dir(BASE_ROOT.DATA_DIR.'cache/admintemplates') && @mkdir(BASE_ROOT.DATA_DIR.'cache/admintemplates',0777);
		template_compile($tpl_file,$compiledtplfile);
    	}
	return $compiledtplfile;
}

function template($tpl, $ext = 'tpl.php') {
	$tpl_file = THEME_ROOT.$tpl.'.'.$ext;
	$compiledtplfile = DATA_DIR.'cache/templates/'.str_replace('/', '_', $tpl).'.tpl.php';
	if(!file_exists($compiledtplfile) || @filemtime($tpl_file) > @filemtime($compiledtplfile)){
    		!is_dir(BASE_ROOT.DATA_DIR.'cache/templates') && @mkdir(BASE_ROOT.DATA_DIR.'cache/templates',0777);
		template_compile($tpl_file,$compiledtplfile);
    	}
	return $compiledtplfile;
}

function template_compile($tpl_file, $compiledtplfile) {
	if (!file_exists($tpl_file)) {
		exit("template file ".$tpl_file." no exists!");
	}
	$str = @file_get_contents ($tpl_file);
	$str = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $str);
        $str = str_replace("{LF}", "<?php echo \"\\n\"; ?>", $str);
        $str = preg_replace('/\\$(\w+):(\w+)/is','$\\1->\\2',$str);
        $str = preg_replace('/\\$(\w+)\.(\w+)/is','$\\1["\\2"]',$str);
	$str = preg_replace ( "/\{template\s+(.+)\}/", "<?php include template(\"\\1\"); ?>", $str );
 	$str = preg_replace ( "/\{admintemplate\s+(.+)\}/", "<?php include admintemplate(\"\\1\"); ?>", $str );
 	$str = preg_replace ( "/\{include\s+(.+)\}/", "<?php include \\1; ?>", $str );
	$str = preg_replace ( "/\{php\s+(.+)\}/", "<?php \\1?>", $str );
	$str = preg_replace ( "/\{echo\s+(.+?)\}/", "<?php echo \\1; ?>", $str);
	$str = preg_replace ( "/\{if\s+(.+?)\}/", "<?php if(\\1) { ?>", $str );
	$str = preg_replace ( "/\{else\}/", "<?php } else { ?>", $str );
	$str = preg_replace ( "/\{elseif\s+(.+?)\}/", "<?php } elseif (\\1) { ?>", $str );
	$str = preg_replace ( "/\{\/if\}/", "<?php } ?>", $str );
	$str = preg_replace("/\{for\s+(.+?)\}/","<?php for(\\1) { ?>",$str);
	$str = preg_replace("/\{\/for\}/","<?php } ?>",$str);
	$str = preg_replace("/\{\+\+(.+?)\}/","<?php ++\\1; ?>",$str);
	$str = preg_replace("/\{\-\-(.+?)\}/","<?php ++\\1; ?>",$str);
	$str = preg_replace("/\{(.+?)\+\+\}/","<?php \\1++; ?>",$str);
	$str = preg_replace("/\{(.+?)\-\-\}/","<?php \\1--; ?>",$str);
	$str = preg_replace ( "/\{loop\s+(\S+)\s+(\S+)\}/", "<?php if(is_array(\\1)) foreach(\\1 AS \\2) { ?>", $str );
	$str = preg_replace ( "/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}/", "<?php if(is_array(\\1)) foreach(\\1 AS \\2 => \\3) { ?>", $str );
	$str = preg_replace ( "/\{\/loop\}/", "<?php } ?>", $str );
	$str = preg_replace ( "/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str );
	$str = preg_replace ( "/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str );
	$str = preg_replace ( "/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/", "<?php echo \\1;?>", $str );
	$str = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/es", "addquote('<?php echo \\1;?>')",$str);
	$str = preg_replace ( "/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php echo \\1;?>", $str );
	$str = preg_replace("/\{url\s+(.+?)\}/is", "<?php echo url(\"\\1\");?>",$str);
	$str = preg_replace("/\{lang\s+(.+?)\}/is", "<?php echo lang::get('\\1');?>",$str);
	
	$str = "<?php if(!defined('IN_SYSTEM')) exit('Access Denied'); ?>" . $str;
	$strlen = file_put_contents ($compiledtplfile, $str );
	chmod ($compiledtplfile, 0777);
}        
function addquote($str) {
	return str_replace ( "\\\"", "\"", preg_replace ( "/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $str ) );
}

function ubb_decode($str=null) {
	global $_G;
	$str = str_replace(array('[b]','[/b]'),array('<b>','</b>'),$str);
	$str = eregi_replace('\[img]([^\[]*)\[/img]','<img src="'.DATA_DIR.'files/'.'\\1" onload="resize_img(this)" />',$str);
	$str = eregi_replace('\[upload=([0-9]+)]',$_G['settings']['siteurl'].'/attachment.php?id=\\1',$str);
	$str = eregi_replace('\[img]([^\[]*)\[/img]','<img src="\\1" onload="resize_img(this)" />',$str);
	$str = eregi_replace('\[url=([^\[]*)]([^\[]*)\[/url]','<a href="\\1" title="\\2" target="_blank">\\2</a>',$str);
	$str = eregi_replace('\[file]([^\[]+)\[/file]','<a href="\\1">点击下载附件</a>',$str);
	return $str;
}

function page_not_found() {
	if ( file_exists(THEME_ROOT.'404.tpl.php') ) {
		include template('404');
	} else {
		header("HTTP/1.1 404 Not Found\n");
		header("Date: ".gdate('D, d M Y H:i:s',TIMESTAMP)." GMT\n");
		echo '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL '.$_SERVER['SCRIPT_NAME'].' was not found on this server.</p>
<p>Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.</p>
</body>
</html>
';
	}
	exit;
}
/**
 * 分页
 * @param 
 */
function pager ($num = 0,$prepage = 10,$curpage = 1,$url = '', $rewritemode = false, $pagenum = 10) {
	$pagestr = '';
	$realpages = 1;
	$page = getGP('page');
	isset($page) && $curpage = max(1, intval($page));
	
	$url = $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
	if(preg_match('/[&|\?]?page=\w+/i', $url) > 0) {
		$url= preg_replace('/[&|\?]?page=\w+/i', '', $url);
	}
	
	$url .= strspn('?',$url) ? (substr($url,-1,1)=='?'?'':'&' ): '?';
	if ($num > $prepage) {
		$realpages = @ceil($num/$prepage);		
		if ($realpages < $pagenum) {
			$from = 1;
			$to = $realpages;
		} else {
			$offset = 5;
			$from = $curpage - $offset;
			$to = $from + $pagenum;
			if ($from < 1) {
				$from = 1;
				$to = $from + $pagenum - 1;
			} elseif ($to > $realpages) {
				$to = $realpages;
				$from = $realpages - $pagenum + 1;
			}
		}
		$pagestr .= '<span>'.$num.'</span>';
		if ($curpage > $pagenum) $pagestr .= '<a href="'.url($url.'page=1').'">1...</a>';
		if ($curpage > 1) $pagestr .= '<a href="'.url($url.'page='.($curpage-1)).'">&lsaquo;&lsaquo;</a>';
		for ($i = $from; $i <= $to; $i++) {
			if ($i == $curpage) {
				$pagestr .= '<span class="on">'.$i.'</span>';
			} else {
				$pagestr .= '<a href="'.url($url.'page='.$i).'">'.$i.'</a>';
			}
		}
		if ($curpage < $realpages) $pagestr .= '<a href="'.url($url.'page='.($curpage+1)).'">&rsaquo;&rsaquo;</a>';
		if ($realpages > $to) $pagestr .= '<a href="'.url($url.'page='.$realpages).'">'.$realpages.'...</a>';
		if ($realpages > 1 && !$rewritemode) $pagestr .= '<input type="text" title="'.lang::get('page_tips','user').'" size="3" class="go" onkeydown="if (event.keyCode==13) {window.location=\''.$url.'page=\'+this.value;return false;}" />';
		$pagestr = '<div class="multipage">'.$pagestr.'</div>';
	}
	return $pagestr;
}

function is_banname($username) {
	global $_G;
	$banname = explode(',', $_G['settings']['user']['banname']);
	if (count($banname)) {
		foreach ($banname as $val) {
			if (empty($val)) continue;
			if (strpos($username, $val) !== false) {
				return true;
			}
		}
	}
	return false;
}

function is_email($email) {
	if (preg_match('/^[0-9a-z]+[0-9a-z_\.\-]*@[0-9a-z\-]+(\.[a-z]{2,4}){1,2}$/i',$email)) {
		return true;
	}
	return false;
}

function is_username($username) {
	$badchars = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','$','(',')','%','@','+','?',';','^');
	foreach ($badchars as $char) {
		if (strpos($username,$char) !== false) {
			return false;
		}
	}
	return true;
}

function is_phone($p){
	return preg_match('/^(\+)?(86)?0?1\\d{10}$/',$p) ? true : false; 
}
function is_url($str){   
	return (preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/",$str)) ? true : false;   
}   

function authcode($str, $method = 'ENCODE') {
	return ($method == 'ENCODE' ? base64_encode($str) : base64_decode($str));
}

function my_serialize($data) {
	return add_slashes(serialize(del_slashes($data)));
}

function link_tags($message,$tags) {
	foreach ($tags as $key => $tag) {
		$message = preg_replace("/(?<=[\s\"\]>()]|[\x7f-\xff]|^)(".preg_quote($tag, '/').")([.,:;-?!()\s\"<\[]|[\x7f-\xff]|$)/siUe","tagfont('\\1','\\2')",$message,1);
	}
	return $message;
}

function tagfont($tag,$code) {
	return '<a href="./index.php?tag='.rawurlencode($tag).'" title="查看有关“'.$tag.'”的文章">'.$tag.'</a>'.$code;
}

//更新配置信息
function settings_update($varname, $value) {
	global $_G;
	$_G['db']->query("UPDATE ".DB_PREFIX."settings SET `value` = '$value' WHERE `name` = '$varname'");
	return $db->affected_rows();
}

//删除配置信息
function settings_delete($varname) {
	global $_G;
	if ( !eregi('^[a-z0-9]+$', $varname) ) return false;
	$_G['db']->query("DELETE FROM ".DB_PREFIX."settings WHERE `name` = '$varname'");
	return $_G['db']->affected_rows();
}
function vd($v=null) {
	echo '<pre>';
	print_r($v);
	echo '</pre>';
	exit;
}
function p($v) {
	print_R($v);
}

function iswriteable($var) {
	$result = false;
	if ( !is_dir($var) ) {
		@mkdir($var, 0777);
	}
	if ( is_dir($var) ) {
		$var .= 'test.html';
		if ( ($fp=@fopen($var, 'wb')) && (@fwrite($fp, 'test')) ) {
			@fclose($fp);
			@unlink($var);
			$result = true;
		}
	}
	return $result;
}
function theme($file=null) {
	if(file_exists(THEME_ROOT.$file)) {
		return THEME_URL.$file;
	}
}
function script($file=null) {
	if(file_exists(BASE_ROOT.'/static/script/'.$file)) {
		return '<script type="text/javascript" src="'. BASE_URL.'static/script/'.$file .'"></script>';
	}
}
function go($location=null) {
	if(isset($_REQUEST['destination'])) {
    		$location = $_REQUEST['destination'];
	} else if(!$location){
	    	global $_G;
	    	if(!$_G['gourl']){
	    		$location = BASE_URL;
	    	}else{
	    		$location = $_G['gourl'];
	    	}
	}else{
    		$location = url($location);
	}
	header("location: $location");
	exit();
}
function url($url){
	global $_G;
	if($_G['settings']['seo']['rewrite']) {
		static $alias=array();
		if(empty($alias)){
			$alias=$_G['cache']->get('alias');
			$alias=array_flip($alias);
		}
		$pattern = array();
		
		$pattern['category'] = '/(\w+).php\?id=([0-9a-z\-_]+)&page=([0-9a-z\-_]+)/i';
		$pattern['article_id'] = '/article.php\?id=([0-9a-z\-_]+)/i';
		$pattern['article_id1'] = '/index.php\?m=article&id=([0-9a-z\-_]+)/i';
		$pattern['category1'] = '/index.php\?m=(\w+)&id=([0-9a-z\-_]+)/i';
		$pattern['article'] = '/(\w+).php\?id=([0-9a-z\-_]+)/i';
		$pattern['index_page'] = '/index.php\?page=([0-9a-z\-_]+)/i';
		$pattern['article_page'] = '/(\w+).php\?page=([0-9a-z\-_]+)/i';
		
//		$pattern['home_3'] = '/home.php\?f=([0-9a-z\-_]+)&gid=([0-9a-z\-_]+)/i';
//		//日志 ajax删除
//		$pattern['home_4'] = '/home.php\?f=([0-9a-z\-_]+)&a=(\w+)&ajax=1&id=([0-9a-z\-_]+)/i';
//		//财务
//		$pattern['home_7'] = '/home.php\?f=([0-9a-z\-_]+)&a=(\w+)&t=(\w+)&ajax=1&id=([0-9a-z\-_]+)/i';
//		$pattern['home_5'] = '/home.php\?f=([0-9a-z\-_]+)&a=(\w+)&t=(\w+)&ajax=1/i';
//		$pattern['home_6'] = '/home.php\?f=([0-9a-z\-_]+)&a=(\w+)&t=(\w+)/i';
//		
//		$pattern['home_2'] = '/(\w+).php\?f=([0-9a-z\-_]+)&a=(\w+)&id=([0-9a-z\-_]+)/i';
//		$pattern['home'] = '/(\w+).php\?f=([0-9a-z\-_]+)&a=(\w+)/i';
//		$pattern['home_8'] = '/(\w+).php\?f=([0-9a-z\-_]+)&page=([0-9a-z\-_]+)/i';
//		$pattern['user_1'] = '/(\w+).php\?f=([0-9a-z\-_]+)&uid=([0-9a-z\-_]+)&k=([0-9a-zA-Z\-_=]+)/i';
//		$pattern['home_1'] = '/(\w+).php\?f=([0-9a-z\-_]+)/i';
//		$pattern['allphp'] = '/(\w+).php/i';
	
		$replace = array();
		$replace['category'] = '\\1-\\2-\\3.html';
//		$replace['allphp'] = '\\1.html';
		$replace['article_id'] = '\\1';
		$replace['article_id1'] = '\\1';
		$replace['article'] = '\\1-\\2.html';
		$replace['category1'] = '\\1-\\2.html';
		$replace['index_page'] = 'p\\1';
		$replace['article_page'] = '\\1/p\\2';
//		$replace['home_2'] = '\\1-\\2-\\3-\\4.html';
//		$replace['home_3'] = 'home-\\1-gid-\\2.html';
//		$replace['home_4'] = 'home-\\1-\\2-1-\\3.html?';
//		$replace['home_5'] = 'home-\\1-\\2-t-\\3-1.html';
//		$replace['home_6'] = 'home-\\1-\\2-t-\\3.html';
//		$replace['home_8'] = '\\1-\\2-page-\\3.html';
//		$replace['home_7'] = 'home-\\1-\\2-t-\\3-1-\\4.html';
//		$replace['home'] = '\\1-\\2-\\3.html';
//		$replace['user_1'] = '\\1-\\2-\\3-k-\\4.html';
//		$replace['home_1'] = '\\1-\\2.html';
		
		foreach($pattern as $k=>$v){
			if(preg_match($v,$url,$match)){
				if( $match['1'] == 'category' && isset($alias[$match['2'].'.category'])){
					$url=$alias[$match['2'].'.category'];
					if($match['3'])$url.='/p'.$match['3'];
					break;
				}
				
				if($k == 'article_id' && isset($alias[$match['1'].'.article'])){
					$url=$alias[$match['1'].'.article'];
					break;
				}
				$url = preg_replace($v, $replace[$k], $url);
				break;
			}
		}
		$pattern = $replace = array();
		unset($pattern,$replace,$urls);
	}
	return $url;
}
function access_denied() {
	header('HTTP/1.1 403 Forbidden');
	error(Lang::get('access_denied'),url('index.php'));
}

function check_access($access=null) {
	if ( !ISADMIN && ican($access) ) {
		access_denied();
	}
}

function recache($cachestr = '') {
	require_once(libfile('cache.php'));
	if (!$cachestr) {
		$cachelist = array('settings','category','usergroups','archive','lastest_article','commend_article','lastest_comment','nav','tags','page');
	} else {
		$cachelist = explode(',',$cachestr);
	}
	foreach ($cachelist as $cache) {
		$cachename = $cache.'_recache';
		if (function_exists($cachename)) {
			$cachename();
		}
	}
}

function editor($id, $name, $content='', $item='default', $width='100%', $height='300px',$loadjs = false) {
	$html = '';
	$loadjs && $html .= '<script type="text/javascript" charset="utf-8" src="'.BASE_URL.'static/editor/kindeditor.js"></script>'."\r\n";
	$html .= "<script type=\"text/javascript\">\r\n";
	$html .= "var editor;\r\n";
	$html .= "\t	KindEditor.ready(function(K) {\r\n";
	$html .= "\t		editor = K.create('#$id',{allowImageUpload:false,allowFlashUpload:false,allowMediaUpload:false,allowFileUpload:false,});\r\n";
	$html .= "\t	});";
	$html .= "</script>\r\n";
	$html .= "<textarea id=\"$id\" name=\"$name\" style=\"width:$width;height:$height;\">$content</textarea>";
	return $html;
}

function get_category_options($selid = 0,$type=0,$myid=0,$adds='') {
	global $_G;
	get_cache('category');
	$html = $selected = '';

	foreach ($_G['caches']['category'] as $key => $val) {
		if ( !empty($val['redirect']) || $val['type'] !=$type ) continue;
		if(!ISADMIN && $val['access'] >0 && $val['access'] !=$_G['users']['groupid']) continue;
		if($val['pid'] == $myid) $child[$key] = $val;
	}
	
	$number=1;
	if(is_array($child)){
		$total = count($child);
		foreach($child as $id=>$a){
			$spacer = $adds ? $adds: '';
			$selected = $id==$selid ? 'selected' : '';
			$html.= '<option value="'.$id.'" '.$selected.'>'.$spacer.$a['catename'].'</option>';
			$html.= get_category_options($selid, $type, $id, $adds.'&nbsp;');
			$number++;
		}
	}
	return $html;
}

function read_dir($path) {
	$dirs = array();
	if (is_dir($path)) {
		if ($d = opendir($path)) {
			while ( ($dir = readdir($d)) !== false ) {
				if ( $dir != '.' && $dir != '..' ) {
					if ( is_dir($path.$dir) ) {
						$dirs[] = $path.$dir;
					}
				}
			}
		}
		@closedir($d);
	}
	return $dirs;
}

function module_exists($module=null) {
	if(file_exists(BASE_ROOT.'./modules/'.$module.'.php')) {
		return true;
	}
	return false;
}

function m($module=null) {
	if(file_exists(BASE_ROOT.'./modules/'.$module.'.php')) {
		include_once(BASE_ROOT.'./modules/'.$module.'.php') ;
	}
}

function tree($trees=array()) {
	if(!is_array($trees) || empty($trees)) {
		return $trees;
	}
	foreach($trees as $pk=>$parent_tree) {
		foreach($parent_tree as $ck => $child_tree ) {
			if(isset($trees[$ck])) {
				$trees[$pk][$ck]['child'] = $trees[$ck];
				unset($trees[$ck]);
			}
		}
	}
	return $trees;
}
/**
 * 语言函数
 * @param string $l  语言
 * @param string $type 类型/模块
 * @param array $vars  替换变量,数组键值格式 array('username'=>'John'),将替换字符串{username}为John
 */
function l($l=null,$type=null,$vars=null) {
	$return = Lang::get($l,$type);
	if($vars && is_array($vars)) {
		$searchs = $replaces = array();
		foreach($vars as $k => $v) {
			$searchs[] = '{'.$k.'}';
			$replaces[] = $v;
		}
		$return = str_replace($searchs, $replaces, $return);
	}
	return $return;
}
/**
 * 发送邮件，发送失败时会在logs目录下SMTP.txt存储失败信息
 * @param string $toemail  接收者
 * @param string $subject 主题
 * @param string $message 内容
 * @param string $from 发件人，默认站点管理员邮箱,若为空则从ini_get('sendmail_from') 获得
 * @return TRUE OR FALSE
 */
function sendmail($toemail=null, $subject=null, $message=null, $from = '') {
	global $_G;
	$mails = unserialize( $_G['settings']['mail']['mail'] );
	$smtps = unserialize(decrypt( $_G['settings']['mail']['smtp'] ));
	foreach( $smtps['server'] as $k => $v ){
		if( !$v ) unset( $smtps['server'][$k] );
	}
	
	if($mails['type'] != 1) {
		$rid = array_rand((array_filter($smtps['server'])));
		$mail['server'] = $smtps['server'][$rid];
		$mail['port'] = $smtps['port'][$rid];
		$mail['auth'] = isset($smtps['auth'][$rid]) ? $smtps['auth'][$rid] : 0;
		$mail['from'] = $smtps['from'][$rid];
		$mail['auth_username'] = $smtps['auth_username'][$rid];
		$mail['auth_password'] = $smtps['auth_password'][$rid];
	}
	$message = preg_replace("/href\=\"(?!http\:\/\/)(.+?)\"/i", 'href="'.$_G['settings']['siteurl'].'\\1"', $message);
	$charset = CHARSET;
$message = <<<EOT
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=$charset">
<title>$subject</title>
</head>
<body>
$subject<br />
$message
</body>
</html>
EOT;

	$maildelimiter = $mails['maildelimiter'] == 1 ? "\r\n" : ($mails['maildelimiter'] == 2 ? "\r" : "\n");
	$mailusername = isset($mails['mailusername']) ? $mails['mailusername'] : 1;
	$mail['port'] = $mail['port'] ? $mail['port'] : 25;
	$mail['type'] = $mails['type'] ? $mails['type'] : 1;

	if(!isset($_G['settings']['adminemail'])) {
		$_G['settings']['adminemail'] = ini_get('sendmail_from');
	}
	if(!$_G['settings']['adminemail'] ){
		setlog('SMTP', "admin email not set");
		return ;
	}
	$email_from = $from == '' ? '=?'.CHARSET.'?B?'.base64_encode($_G['settings']['sitename'])."?= <".$_G['settings']['adminemail'].">" : (preg_match('/^(.+?) \<(.+?)\>$/',$from, $mats) ? '=?'.CHARSET.'?B?'.base64_encode($mats[1])."?= <$mats[2]>" : $from);

	$email_to = preg_match('/^(.+?) \<(.+?)\>$/',$toemail, $mats) ? ($mailusername ? '=?'.CHARSET.'?B?'.base64_encode($mats[1])."?= <$mats[2]>" : $mats[2]) : $toemail;

	$email_subject = '=?'.CHARSET.'?B?'.base64_encode(preg_replace("/[\r|\n]/", '', '['.$_G['settings']['sitename'].'] '.$subject)).'?=';
	$email_message = chunk_split(base64_encode(str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $message))))));
	$host = $_SERVER['HTTP_HOST'];
	$headers = "From: $email_from{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: $host {$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: text/html; charset=".CHARSET."{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}";
	if($mails['type'] == 1) {
		if(function_exists('mail') && @mail($email_to, $email_subject, $email_message, $headers)) {
			return true;
		}
		return false;

	} elseif($mails['type'] == 2) {
		if(!$fp = @fsockopen($mail['server'], $mail['port'], $errno, $errstr, 4)) {
			setlog('SMTP', "(".$mail['server'].":".$mail['port'].") CONNECT - Unable to connect to the SMTP server");
			return false;
		}
		stream_set_blocking($fp, true);

		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != '220') {
			setlog('SMTP', $mail['server'].":".$mail['port']." CONNECT - $lastmessage");
			return false;
		}
		fputs($fp, ($mail['auth'] ? 'EHLO' : 'HELO')." apps\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {
			setlog('SMTP', $mail['server'].":".$mail['port']." HELO/EHLO - $lastmessage");
			return false;
		}

		while(1) {
			if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {
				break;
			}
			$lastmessage = fgets($fp, 512);
		}

		if($mail['auth']) {
			fputs($fp, "AUTH LOGIN\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 334) {
				setlog('SMTP', "(".$mail['server'].":".$mail['port'].") AUTH LOGIN - $lastmessage");
				return false;
			}

			fputs($fp, base64_encode($mail['auth_username'])."\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 334) {
				setlog('SMTP', "(".$mail['server'].":".$mail['port'].") USERNAME - $lastmessage");
				return false;
			}

			fputs($fp, base64_encode($mail['auth_password'])."\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 235) {
				setlog('SMTP', "(".$mail['server'].":".$mail['port'].") PASSWORD - $lastmessage");
				return false;
			}
			$email_from = $mail['from'];
		}

		fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 250) {
				setlog('SMTP', "(".$mail['server'].":".$mail['port'].") MAIL FROM - $lastmessage");
				return false;
			}
		}

		fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $toemail).">\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $toemail).">\r\n");
			$lastmessage = fgets($fp, 512);
			setlog('SMTP', "({$mail[server]}:{$mail[port]}) RCPT TO - $lastmessage", 0);
			return false;
		}

		fputs($fp, "DATA\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 354) {
			setlog('SMTP', "({$mail[server]}:{$mail[port]}) DATA - $lastmessage", 0);
			return false;
		}

		$headers .= 'Message-ID: <'.gdate('YmdHs').'.'.substr(md5($email_message.microtime()), 0, 6).rand(100000, 999999).'@'.$_SERVER['HTTP_HOST'].">{$maildelimiter}";

		fputs($fp, "Date: ".gdate('r')."\r\n");
		fputs($fp, "To: ".$email_to."\r\n");
		fputs($fp, "Subject: ".$email_subject."\r\n");
		fputs($fp, $headers."\r\n");
		fputs($fp, "\r\n\r\n");
		fputs($fp, "$email_message\r\n.\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			setlog('SMTP', "({$mail[server]}:{$mail[port]}) END - $lastmessage", 0);
		}
		fputs($fp, "QUIT\r\n");

		return true;
	} 
}
function get_styles() {
	global $_G;
	$style = '<link href="'.theme('css/style.css').'" rel="stylesheet" type="text/css" />';
	if(isset($_G['styles'])) {
		foreach((array)$_G['styles'] as $k=>$v) {
			$style .= '<link href="'.$v.'" rel="stylesheet" type="text/css" />';
		}
	}
	return $style;
}

function get_scripts() {
	global $_G;
	$scripts = script('jquery.js');
	$scripts .= script('common.js');
	if(isset($_G['scripts'])) {
		foreach((array)$_G['scripts'] as $k=>$v) {
			if($k === 'settings') {
				$scripts .= '<script type="text/javascript">'.$v.'</script>';
			}else{
				$scripts .= '<script type="text/javascript" src="'.$v.'"></script>';
			}
		}
	}
	return $scripts;
}

function setlog($type,$log=''){
	!$type && $type='syslog';
	if(!file_exists(BASE_ROOT.DATA_DIR.'logs/'.$type.'.txt')) {
		if(!is_dir(BASE_ROOT.DATA_DIR.'logs')){
			make_dir(BASE_ROOT.DATA_DIR.'logs', 0777);
		}
	}
	return file_put_contents(BASE_ROOT.DATA_DIR.'logs/'.$type.'.txt', "\n".gdate('Y-m-d H:i:s',TIMESTAMP).$log, FILE_APPEND );
}
/**
 * 获取邮件内容模板并解析
 * @param string $type 类型
 * @param string $key 值为 title 或body
 * @param array $token 替换变量,形式为 @变量名=>值
 */
function get_email($type,$key,$token=array()){
	static $systememail;
	global $_G;
	$token = array_merge(array('@sitename'=>$_G['settings']['sitename'],'@siteurl'=>$_G['settings']['siteurl']?$_G['settings']['siteurl']:BASE_URL,'@uid'=>$_G['uid'],'@username'=>$_G['username']),(array)$token);
	if(isset($systememail[$type][$key])) {
		return strtr($systememail[$type][$key],$token);
	}
	$systememail[$type] = lang::get($type,'email');
	return strtr($systememail[$type][$key],$token);
}
/**
 * 类别下的内容
 * @param int $id 类别ID
 * @param string $limit 获取条数
 */
function get_category_contents($id=0,$limit=15){
	if(!intval($id))return array();
	global $_G;
	$contents = $_G['cache']->get($id.'_'.$limit,'category');
	if(!$contents){
		$contents = array();
		$type=$_G['db']->result("SELECT type FROM ".DB_PREFIX."category where cid=".intval($id));
		switch($type) {
			case '0'://文章
				$contents = array();
				$sql = "SELECT a.aid,a.title,a.default_image,a.summary,c.catename FROM ".DB_PREFIX."article a LEFT JOIN ".DB_PREFIX."category c ON a.cid=c.cid WHERE c.type=0 AND c.cid= '{$id}' AND c.status=0 AND a.ischeck=1 ORDER BY a.aid DESC ";
				$query = $_G['db']->page_query($sql,$limit);
				while($data = $_G['db']->fetch_array($query)) {
					$contents[] = $data ;
				}
			break;
			case '1'://网址链接
				$contents = array();
				$sql = "SELECT l.*,c.catename,u.username FROM ".DB_PREFIX."link l LEFT JOIN ".DB_PREFIX."category c ON l.cid=c.cid LEFT JOIN ".DB_PREFIX."users u ON l.uid=u.uid WHERE c.type=1 AND c.cid= '{$id}' AND l.visible=1 AND c.status=0 ORDER BY l.listorder DESC ";
				$query = $_G['db']->page_query($sql,$limit);
				while($data = $_G['db']->fetch_array($query)) {
					$contents[] = $data ;
				}
				break;	
			default:

			break;
		}
		if(!empty($contents))
		$_G['cache']->set($id.'_'.$limit,$contents,'category');
	}
	return $contents;
}

function loadialog(){
	global $_G;
	$_G['scripts']['dialog'] =  BASE_URL.'static/script/dialog.js';
	$_G['styles']['dialog'] =  BASE_URL.'static/style/dialog.css';
}

function table($table=null){
	return ' '.DB_PREFIX.$table.' ';
}

function checkpoint($uid=0,$point=array()){
	if(!$uid || empty($point)){
		return false;
	}
	if($point['point1']<1 && $point['point2']<1 &&$point['point3']<1){
			return false;
	}
	switch($point['cycletype']){
		case '2':
			$where=" AND dateline>".gtime(gdate("Y-m-d",TIMESTAMP));
			break;
		case '3':
			$where=" AND dateline>".gtime(gdate("Y-m-d",TIMESTAMP-86400*6));
			break;	
		case '4':
			$where=" AND dateline>".gtime(gdate("Y-m",TIMESTAMP));
			break;	
		default:
			$where='';
	}
	global $_G;
	$times=$_G['db']->result("SELECT count(*) FROM".table('point_log')."WHERE operation='".$point['rule']."' AND uid='$uid'".$where);
	if($point['cycletime'] && $point['cycletime']<=$times){
		return false;
	}
	return true;
}

function point($action,$refer=array()){
	global $_G;
	switch($action) {
		case 'inviteuser':
		case 'userregist':
		case 'signinsite':	
			if($refer['uid']){
				$point=$_G['db']->fetch_one_array("SELECT * FROM".table('point_rule')."WHERE rule='".$action."' LIMIT 1");
				if(checkpoint($refer['uid'],$point)){
					$data = array(
						'uid' => $refer['uid'],
						'operation' => $point['rule'],
						'point1'	=> $point['point1'],
						'point2'	=> $point['point2'],
						'point3'	=> $point['point3'],
						'relatedid' =>$refer['relatedid '],
						'dateline'	=> TIMESTAMP,
					);
					$_G['db']->insert("point_log",$data);
					$total = $_G['db']->fetch_one_array("SELECT point1,point2,point3 FROM".table('user_stat')."WHERE uid='".$uid."' ");
					$_G['db']->update('user_stat',array('point1'=>"point1+$point[point1]",'point2'=>"point2+$point[point2]",'point3'=>"point3+$point[point3]"),array('uid'=>$uid));
				}
			}
			break;
		case 'pointbuy':
			if(empty($refer) || !$refer['uid'] || $refer['amount']<1 || $refer['status']>0){
				return '';
			}
			if(!$_G['settings']['point']['pointuse']){
				return '';
			}
			$data = array(
				'uid' => $refer['uid'],
				'operation' => 'pointbuy',
				$_G['settings']['point']['pointuse']	=> $refer['amount'],
				'dateline'	=> TIMESTAMP,
			);
			$_G['db']->insert("point_log",$data);
			$total = $_G['db']->result("SELECT ".$_G['settings']['point']['pointuse']." FROM".table('user_stat')."WHERE uid='".$refer['uid']."' ");
			$_G['db']->update('user_stat',array($_G['settings']['point']['pointuse']=>$total+$refer['amount']),array('uid'=>$refer['uid']));
			break;
	}
}

function checkrobot($useragent = '') {
	$spiders = array('bot', 'crawl', 'spider' ,'slurp', 'sohu-search', 'lycos', 'robozilla');
	$browsers = array('msie', 'netscape', 'opera', 'konqueror', 'mozilla');
	$useragent = strtolower(empty($useragent) ? $_SERVER['HTTP_USER_AGENT'] : $useragent);
	if(strpos($useragent, 'http://') === false){
		foreach($browsers as $v){
			if( strpos($useragent, $v) ) {
				return false;
			}
		}
	}else{
		foreach($spiders as $v){
			if( strpos($useragent, $kw_spiders) ) {
				return true;
			}
		}
	}
}

/**
 * 图片缩略图
 */
function make_thumb($id){
	global $_G;
	$file = $_G['db']->result("SELECT filepath FROM ".DB_PREFIX."files WHERE fid = '".$id."' LIMIT 1");
	
	if(!file_exists(BASE_ROOT.DATA_DIR.'files/'.$file)){
		return ;
	}
	if(get_config('front_thumb_width','upload')<1 || get_config('front_thumb_height','upload')<1){
		return $file;
	}
	include('upload.php');
	$upload = new upload($_G['settings']['upload']['allow_type'], $_G['settings']['upload']['file_size'], 'upfile');
	$upload->set_dir(BASE_ROOT.DATA_DIR.'files/', $_G['settings']['upload']['dir_rule']);
	$upload->set_thumb(intval(get_config('front_thumb_width','upload')), intval(get_config('front_thumb_height','upload')));
	@unlink($upload->dir.'thumb_'.$file);
	$filename = basename(BASE_ROOT.DATA_DIR.'files/'.$file);
	if ($upload->create_thumb(BASE_ROOT.DATA_DIR.'files/'.$file,$upload->dir.'thumb_'.$filename)) {
		$thumb = str_replace(DATA_DIR.'files/','', $upload->dir.'thumb_'.$filename); 
		$thumb = str_replace(BASE_ROOT,'', $thumb); 
		$_G['db']->update('files',array('thumb'=>$thumb),array('fid'=>$id));
	}
	return $thumb;
}

/**
 * 压缩HTML文件
 */
function compress_html($string) {
	$string = str_replace("\r\n", '', $string); //清除换行符 
	$string = str_replace("\n", '', $string); //清除换行符 
	$string = str_replace("\t", '', $string); //清除制表符 
	$pattern = array(
		 "/> *([^ ]*) *</", //去掉注释标记 
		"/[\s]+/", 
		"/<!--[^!]*-->/", 
 		"/\" /", 
		"/ \"/", 
		"'/\*[^*]*\*/'" 
	);
	$replace = array(
		">\\1<", 
		" ", 
		"", 
		"\"", 
		"\"", 
		"" 
	);
	return preg_replace($pattern, $replace, $string); 
}
function price($num){
	return number_format($num,2,'.','');
}
/**
 * 输出JSON并退出当前进程
 * @param array $data 数组，将使用json_encode进行编码
 */
function json($data){
	print_r(json_encode($data));
	exit;
}
function msg($msg=null,$go=null){
	set_cookie('msg',rawurlencode($msg));
	go($go);
}
function password($pass,$authkey){
	return md5(md5($pass.$authkey).$authkey);
}

function save_alias($alias='',$id=0,$type=null){
	if(!$id || !$type || !$alias){
		return ;
	}
	global $_G;
	$eid=$_G['db']->result("SELECT id FROM ".DB_PREFIX."alias WHERE id = '$id' AND atype='$type'");
	if($eid>0){
		$_G['db']->update('alias', array('alias'=>$alias), array('id' => $id,'atype'=>$type));
	}else{
		$_G['db']->insert('alias', array('alias'=>$alias,'id'=>$id,'atype'=>$type));
	}
	$query=$_G['db']->query("SELECT * FROM".table('alias'));
	while($data=$_G['db']->fetch_array($query)){
		$datas[$data['alias']]=$data['id'].'.'.$data['atype'];
	}
	$_G['cache']->set('alias',$datas);
	$datas=array();unset($datas);
}
function get_tags($tid){
	$return=array();
	if($tid){
		global $_G;
		$tids=explode(',',$tid);
		if(!empty($tids)){
			$tags = $_G['cache']->get('tags');
			foreach($tids as $id){
				if(isset($tags[$id]))$return[$id]=$tags[$id];
			}
		}
	}
	return $return;
}

function encrypt($key, $str='xk41czh') {
	$lockstream = 'st=lDEFABCNOPyzghi_jQRST-UwxkVWXYZabcdef+IJK6/7nopqr89LMmGH012345uv';
	$lockLen = strlen($lockstream);
	$lockCount = rand(0,$lockLen-1);
	$randomLock = $lockstream[$lockCount];
	$str = md5($str.$randomLock);
	$key = base64_encode($key);
	$tmpStream = '';
	$i=0;$j=0;$k = 0;
	for ($i=0; $i<strlen($key); $i++) {
		$k = ($k == strlen($str)) ? 0 : $k;
		$j = (strpos($lockstream,$key[$i])+$lockCount+ord($str[$k]))%($lockLen);
		$tmpStream .= $lockstream[$j];
		$k++;
	}
	return $tmpStream.$randomLock;
}

function decrypt($key, $str='xk41czh') {
	$lockstream = 'st=lDEFABCNOPyzghi_jQRST-UwxkVWXYZabcdef+IJK6/7nopqr89LMmGH012345uv';
	$lockLen = strlen($lockstream);
	$txtLen = strlen($key);
	$randomLock = $key[$txtLen - 1];
	$lockCount = strpos($lockstream,$randomLock);
	$str = md5($str.$randomLock);
	$key = substr($key,0,$txtLen-1);
	$tmpStream = '';
	$i=0;$j=0;$k = 0;
	for($i=0; $i<strlen($key); $i++){
		$k = ($k == strlen($str)) ? 0 : $k;
		$j = strpos($lockstream,$key[$i]) - $lockCount - ord($str[$k]);
		while($j < 0){
			$j = $j + ($lockLen);
		}
		$tmpStream .= $lockstream[$j];
		$k++;
	}
	return base64_decode($tmpStream);
}
/**
 * 导航
 * @param int $type 类型
 * @param int $num 数量
 */
function get_nav($type=1,$num=10,$pid=0){
	global $_G;
	$navs=$_G['cache']->get('nav');
	if($type<1 || $type>6)$type=1;
	if($num<1)$num=1;
	if(empty($navs)){
		$navs=$_G['db']->fetch('nav','*',null,'displayorder ASC');
		$_G['cache']->set('nav',$navs);
	}
	foreach($navs as $v){
		if($v['navtype'] != $type || !$v['visible']) continue;
		if($v['access'] && $v['access']!=$_G['groupid']) continue;
		if($pid>0 && $v['parentid']!=$pid) continue;
		if($v['parentid']) {
			$subnavs[$v['parentid']][]=$v;
			continue;
		}
		$nvs[]=$v;
	}
	if( !empty($nvs) ) $nv=array_splice($nvs, 0,$num);
	return array('nvs'=>$nv,'subs'=>$subnavs);
}
/**
 * 钩子
 * @param string $funtion 函数名
 * @param string $module 模块名
 * @param bool $isadmin 是否是管理模块
 */
function hook($function,$module,$isadmin=false){
	static $m=array();
	if( !$m[$module] ) {
		if($isadmin) {
			if(file_exists(ADMIN_ROOT.'admin_'.$module.'.php')){
				include(ADMIN_ROOT.'admin_'.$module.'.php');
			}
		}else{
			m($module);
		}
		$m[$module] =true;
	}
	if( $m[$module] ) {
		$classname = ucfirst($module).'Module';
		$md = new $classname;
		if(function_exists($function)){
			$data=$md->$function();
			return $data;
		}
	}
	return '';
}
function get_block($module=null){
	global $_G;
	return $_G['db']->fetch_all("SELECT * FROM".table('block')."WHERE module='$module'");
}
function block_content($blockid,$num=10){
	global $_G;
	if($blockid<1 || $num<1) return '';
	$data['block']=$_G['db']->fetch('block','*',array('blockid'=>$blockid));
	$query=$_G['db']->query("SELECT * FROM".table('block_data')."WHERE blockid='$blockid' AND status=1 ORDER BY listorder ASC,expiration DESC LIMIT 0,$num");
	while($row=$_G['db']->fetch_array($query)) {
		$row['data']=unserialize($row['data']);
		$data['data'][]=$row;
	}
	return $data;
}
?>